package com.spn.blog.api.filter;

import com.alibaba.fastjson.JSONObject;
import com.spn.blog.common.dao.pojo.LoginUser;
import com.spn.blog.common.utils.JWTUtils;
import com.spn.blog.common.utils.RedisCacheUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // 1获取token
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasText(token)) {
            // 放行，让后面的过滤器执行
            filterChain.doFilter(request, response);
            return;
        }
        // 2解析token
        Map<String, Object> map = JWTUtils.checkToken(token);

        // 3获取userId，redis获取用户信息
        String userId = (String)map.get("userId");
        JSONObject jsonObject = redisCacheUtil.getCacheObject("TOKEN:" + userId);
        LoginUser loginUser = jsonObject.toJavaObject(LoginUser.class);
        if (Objects.isNull(loginUser)) {
            // 有token，但是token过期
            filterChain.doFilter(request, response);
            return;
        }
        // 4封装Authentication
        // 三个参数的构造方法是确定已经登录成功了
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
                = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());

        // 5存入SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        // 放行，让后面的过滤器执行
        filterChain.doFilter(request, response);
    }
}